<template>
	<view class="main-content">
		<van-popup v-model:show="state.show" position="top">
			<view class="search-line">
				<input class="search-input" placeholder="请输入关键字" v-model="state.keyWord" />
				<view class="search-btn" @click="search">查询</view>
				<view class="search-btn" @click="clear">清空</view>
			</view>
		</van-popup>
		<MHeader>
			{{state.pageName}}
			<template #right>
				<view style="display: flex;align-items: center;">
					<input class="search-input" placeholder="请输入关键字" v-model="state.keyWord" @input="debounce(() => search(), 1000)" />
					<van-icon name="plus" size="20" style="margin-left: 20rpx;" @click="toAppend" v-if="state.IsAE" />
				</view>
			</template>
		</MHeader>
		<view class="sum" v-if="state.query.FormId === 'QUQY_DrugOutbound'">
			<view class="">
				实发数量：{{state.list.reduce((preV,next)=>preV+next.F_QUQY_RealQty,0)}}
			</view>
			<view class="">
				价税合计：{{state.list.reduce((preV,next)=>preV+next.F_QUQY_TotalTaxAmount,0)}}
			</view>
		</view>
		<view class="sum" v-show="state.query.FormId === 'QUQY_SalesDeliveryOrder'">
			批次袋数合计：{{ state.list && state.list.length > 0 && state.keyWord ? state.list.reduce((acc, cur) => acc + cur.F_QUQY_TotalApply, 0) : 0 }}
		</view>
		<van-tabs v-model:active="active" @click-tab="tabClick" v-if="state.query.FormId === 'QUQY_GetBreContract'">
			<van-tab :title="item.label" v-for="(item,index) in state.tabs" :key="index"></van-tab>
		</van-tabs>
		<MScrollView :filterFlag="state.filterFlag" :height="state.isChoose?'calc(100% - 180rpx)':'calc(100% - 80rpx)'" ref="msv" :api="kdApis.formQuery" :sInfo="state.info" @list="getList">
			<view class="list-line" v-for="(item,index) in state.list" :key="index" @click="chooseIt(item)">
				<view class="active" v-show="state.isChoose" :style="[state.isM&&{'border-radius':'3rpx'},state.chooseList.findIndex(it => item[state.info.OnlySign] == it[state.info.OnlySign])>-1&&{'background':'#2386ee'}]">
					<van-icon name="success" color="#fff" size="14" />
				</view>
				<!-- 列表组件 -->
				<view style="display: flex;flex-wrap:wrap; 100%;padding: 10rpx 0;">
					<component :is="state.curCom" :info="item" :groupInfo="state.groupInfo" :myInfo="state.myInfo" @remove="removeLine" @audit="auditLine" @unAudit="unAuditLine" @submit="submitForm"></component>
				</view>
			</view>
			<view :style="{'height': (['QUQY_DrugOutbound','QUQY_SalesDeliveryOrder'].includes(state.query.FormId) ? '120rpx' : '30rpx')}"></view>
		</MScrollView>
		<SubmitBtn name="确 认" v-if="state.isChoose" @submit="submit"></SubmitBtn>
	</view>
</template>

<script setup>
	// 1. 有分组信息则显示分组查询
	// 2. 携带分组信息则按照分组查询
	import { reactive, getCurrentInstance, ref, nextTick } from 'vue'
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import { msg, remove, audit, unAudit, confirm } from '/utils/utils.js'
	import kdApis from '/api/modularApi/kdApi.js'
	import base from './base.js'
	import QUQY_SeedPlan from '/views/module/listCard/SeedlingRaisingPlan.vue'
	import QUQY_LossInfoMiao from '/views/module/listCard/SeedlingLoss.vue'
	import QUQY_BreContract from '/views/module/listCard/BreedingContract.vue'
	import QUQY_FeedApplication from '/views/module/listCard/FeedApplication.vue'
	import QUQY_VeterinaryMedicineApplication from '/views/module/listCard/VeterinaryDrugApplication.vue'
	import QUQY_Settle from '/views/module/listCard/SettlementForm.vue'
	import QUQY_YHSettle from '/views/module/listCard/YHSettlementForm.vue'
	import BD_MATERIAL from '/views/module/listCard/BD_MATERIAL.vue'
	import BD_Supplier from '/views/module/listCard/BD_Supplier.vue'
	import BD_UNIT from '/views/module/listCard/BD_UNIT.vue'
	import BD_Customer from '/views/module/listCard/BD_Customer.vue'
	import BAS_PreBaseDataTwo from '/views/module/listCard/BAS_PreBaseDataTwo.vue'
	import BAS_PreBaseDataOne from '/views/module/listCard/BAS_PreBaseDataOne.vue'
	import BD_Empinfo from '/views/module/listCard/BD_Empinfo.vue'
	import ORG_Organizations from '/views/module/listCard/ORG_Organizations.vue'
	import QUQY_DrugOutbound from '/views/module/listCard/DrugOutbound.vue'
	import QUQY_VeterinaryDrugAllot from '/views/module/listCard/VeterinaryDrugAllot.vue'
	import QUQY_SalesDeliveryOrder from '/views/module/listCard/SalesDeliveryOrder.vue'
	import QUQY_VeterinaryDrugStock from '/views/module/listCard/QUQY_VeterinaryDrugStock.vue'
	import QUQY_TransferApplication from '/views/module/listCard/TransferApplication.vue'
	import QUQY_VDInventoryTable from '/views/module/listCard/QUQY_VDInventoryTable.vue'
	import QUQY_GetBreContract from '/views/module/listCard/QUQY_GetBreContract.vue'
	const { proxy } = getCurrentInstance()
	const state = reactive({
		config: proxy.$config,
		query: {},
		pageName: "",
		info: {},
		list: [],
		show: false,
		keyWord: "",
		isChoose: false,
		isM: false,
		IsAE: true,
		chooseList: [],
		curCom: null,
		groupInfo: {},
		fun: null,
		myInfo: {},
		twiceList: [],
		// 养殖合同
		tabs: [
			{ label: '全 部', FR: [] },
			{
				label: '上苗中',
				FR: [
					{ Left: "(", FieldName: "F_QUQY_SMSTATE", Compare: "=", Value: "上苗中", Right: ")", Logic: "and", filterFlag: "jc" },
				]
			},
			{
				label: '完全结算',
				FR: [
					{ Left: "(", FieldName: "F_QUQY_SMSTATE", Compare: "=", Value: "完全结算", Right: ")", Logic: "and", filterFlag: "jc" },
				]
			}
		],
		originFR: []
	})

	const active = ref(1)

	// 动态组件 is 没法使用字符串 -。-！
	const components = reactive({
		QUQY_SeedPlan,
		QUQY_LossInfoMiao,
		QUQY_BreContract,
		QUQY_FeedApplication,
		QUQY_VeterinaryMedicineApplication,
		QUQY_Settle,
		QUQY_YHSettle,
		QUQY_DrugOutbound,
		QUQY_VeterinaryDrugAllot,
		BD_MATERIAL,
		BD_Supplier,
		BD_UNIT,
		BD_Customer,
		BAS_PreBaseDataOne,
		BAS_PreBaseDataTwo,
		BD_Empinfo,
		ORG_Organizations,
		QUQY_SalesDeliveryOrder,
		QUQY_VeterinaryDrugStock,
		QUQY_TransferApplication,
		QUQY_VDInventoryTable,
		QUQY_GetBreContract
	})

	const msv = ref(null)

	onLoad(async (query) => {
		state.list = []
		state.query = query
	})

	onShow(() => {
		state.list = []
		state.pageName = state.query.Name
		state.isChoose = !!state.query.isChoose
		state.IsAE = !!Number(state.query.IsAE)
		// 🍕 财务不允许新增单据
		state.myInfo = uni.getStorageSync('myInfo')
		if (state.myInfo.role.length == 1 && state.myInfo.role[0] == 7) state.IsAE = 0
		if (state.myInfo.role.includes(11) || state.myInfo.role.includes(7)) state.IsAE = 0
		if (state.query.isM) state.isM = !!state.query.isM
		let baseTem = JSON.parse(JSON.stringify(base))
		
		// import 缓存问题，取到数据后再做处理
		handleData(baseTem)
		for (let item of baseTem) {
			if (item.FormId == state.query.FormId) {
				state.info = item
				state.curCom = components[state.query.FormId]
				// 保存一份查询条件
				state.originFR = JSON.parse(JSON.stringify(item.FilterString))
			}
		}
		// 查询条件过滤
		if (state.query.R) {
			let arr = state.query.R.split(',')
			state.info.FilterString = state.info.FilterString.filter(it => arr.includes(String(it.R)) || !it.R)
		}

		// 按照分组查询 刷新不丢失
		if (state.query.Group && state.info.GroupInfo) {
			state.info.FilterString.push({ "Left": "(", "FieldName": state.info.GroupInfo.Field, "Compare": "in", "Value": state.query.Group, "Right": ")", "Logic": "and" })
		}

		// 如果当前基础资料有分组则查询分组信息
		if (state.info.GroupInfo) {
			kdApis.formQuery({
				data: {
					FormId: state.info.GroupInfo.FormId,
					FieldKeys: "FId,FName"
				}
			}).then(res => {
				if (res) {
					res.forEach(it => { state.groupInfo[it.FId] = it.FName })
				}
			})
		}

		const eventChannel = proxy.getOpenerEventChannel()
		eventChannel.on("fun", ([fun, filterFlag, FR, twiceList]) => {
			state.fun = fun
			state.filterFlag = filterFlag
			if (state.query.twice) {
				state.twiceList = twiceList
			}
			if (FR) state.info.FilterString = state.info.FilterString.concat(FR)
		})

		setTimeout(() => {
			let flag = true
			if(window.location.href.includes('FormId=QUQY_Settle') || window.location.href.includes('FormId=QUQY_SeedPlan') || window.location.href.includes('FormId=QUQY_GetBreContract')) {
				try{
					if(state.info.FilterString && state.info.FilterString.length > 0) {
						let memberInfo = uni.getStorageSync('memberInfo')
						state.info.FilterString.map(it=> {
							if(it.FieldName == 'F_QUQY_YWY' && String(it.Value).length > 5 && it.Value == memberInfo.Id) {
								flag = false
							}
						})
					}
					let myInfo = uni.getStorageSync('myInfo')
					if(myInfo.role.includes(7) || myInfo.role.includes(11)) flag = false
				}catch(e){
				}
			}
			if((window.location.href.includes('FormId=QUQY_Settle') || window.location.href.includes('FormId=QUQY_SeedPlan') || window.location.href.includes('FormId=QUQY_GetBreContract')) && flag) {
				msg('未获取人员信息，返回上一页')
				uni.navigateBack()
				return
			}
			if (state.query.FormId === 'QUQY_GetBreContract') {
				tabClick({name:1})
			} else {
				msv.value.reUp(state.twiceList)
			}
		}, 300)
	})

	const tabClick = (val) => {
		state.tabs = reactive([
			{ label: '全 部', FR: [] },
			{
				label: '上苗中',
				FR: [
					{ Left: "(", FieldName: "F_QUQY_SMSTATE", Compare: "=", Value: "上苗中", Right: ")", Logic: "and", filterFlag: "jc" },
				]
			},
			{
				label: '完全结算',
				FR: [
					{ Left: "(", FieldName: "F_QUQY_SMSTATE", Compare: "=", Value: "完全结算", Right: ")", Logic: "and", filterFlag: "jc" },
				]
			}
		])
		const tab = state.tabs[val.name]
		// tab.FR = []
		state.info.FilterString = state.originFR
		let memberInfo = uni.getStorageSync('memberInfo')
		tab.FR.push({ "Left": "(", "FieldName": "F_QUQY_ORGID", "Compare": "=", "Value": memberInfo.F_QUQY_COMPANY_Id, "Right": ")", "Logic": "and" })
		let myInfo = uni.getStorageSync('myInfo')
		if(myInfo.role.includes(3)){
			tab.FR.push({ "Left": "(", "FieldName": "F_QUQY_YWY", "Compare": "=", "Value": memberInfo.Id, "Right": ")", "Logic": "and" })
		}
		state.info.FilterString = tab.FR
		msv.value.reUp(state.twiceList)
	}

	const getList = (list) => {
		console.log(list, '------------');
		state.list = list
	}
    let timer = null;
	const debounce = (fn, delay) => {
        if (timer) clearTimeout(timer)
        timer = setTimeout(function() {
            fn()
        }, delay)
    }
	const search = () => {
		state.show = false
		state.info.FilterString = state.info.FilterString.filter(it => !it.IsTem)
		let FR = [{ "Left": "(", "FieldName": state.info.SearchField, "Compare": "like", "Value": state.keyWord, "Right": ")", "Logic": "", "IsTem": 1 }]
		state.info.FilterString = state.info.FilterString.concat(FR.filter(it => it.Value))
		msv.value.reUp(state.twiceList)
	}

	const clear = () => {
		state.show = false
		state.keyWord = ""
		state.info.FilterString = state.info.FilterString.filter(it => !it.IsTem)
		msv.value.reUp()
	}

	const chooseIt = (it) => {
		if (!state.isChoose) {
			// 进入详情
			uni.navigateTo({
				url: `/views/module/details/${state.query.FormId}?Id=${it.FID}`
			})
			return
		}
		if (state.isM) {
			let index = state.chooseList.findIndex(item => item[state.info.OnlySign] == it[state.info.OnlySign])
			if (index > -1) {
				state.chooseList.splice(index, 1)
			} else {
				state.chooseList.push(it)
			}
		} else {
			state.chooseList = [it]
		}
	}

	const submit = () => {
		if (state.chooseList.length == 0) return msg('请选择至少一项！')
		if (state.fun) state.fun(state.chooseList)
		uni.navigateBack()
	}

	const toAppend = () => {
		uni.navigateTo({
			url: state.info.AEUrl
		})
	}

	// 删除
	const removeLine = (info) => {
		remove(state.info.FormId, null, info.FID, msv.value.reUp)
	}

	// 审核
	const auditLine = (info) => {
		audit(state.info.FormId, null, info.FID, msv.value.reUp)
	}

	// 反审核
	const unAuditLine = (info) => {
		unAudit(state.info.FormId, null, info.FID, msv.value.reUp)
	}

	// 提交
	const submitForm = (info) => {
		confirm('请确认提交 ？').then(() => {
			kdApis.formSubmit({
				formId: state.info.FormId,
				data: {
					Ids: info.FID
				}
			}).then(res => {
				if (res) {
					msg('提交成功！')
					msv.value.reUp()
				}
			})
		}).catch(() => {})
	}
	const handleId = (Id) => {
		let flag = false
		if(!Id && Id.length < 5) {
			msg('未获取人员信息，返回上一页')
			flag = true
		}
		return flag
	}

	// 处理
	const handleData = (baseList) => {
		// 获取某个
		let findIndexFun = (FormId, FR) => {
			let index = baseList.findIndex(it => it.FormId == FormId)
			baseList[index].FilterString = baseList[index].FilterString.concat(FR)
		}

		// 根据角色划分权限
		let myInfo = uni.getStorageSync('myInfo')
		let userInfo = uni.getStorageSync('userInfo')
		let memberInfo = uni.getStorageSync('memberInfo')
		

		// 🍕 养殖批次
		let FR_YZPC = [
			{ Left: "(", FieldName: "F_QUQY_Driver", Compare: "=", Value: userInfo.F_QUQY_Driver_Id, Right: ")", Logic: "and", R: 1 },
			{ "Left": "(", "FieldName": "F_QUQY_Saleman", "Compare": "=", "Value": memberInfo.Id, "Right": ")", "Logic": "and", R: 3 },
			{ Left: "(", FieldName: "FUseOrgId", Compare: "=", Value: memberInfo.F_QUQY_COMPANY_Id, Right: ")", Logic: "and", R: 5 },
			{ "Left": "(", "FieldName": "F_QUQY_JSY", "Compare": "=", "Value": memberInfo.Id, "Right": ")", "Logic": "and", R: 5 },
		]
		findIndexFun('BAS_PreBaseDataOne', FR_YZPC)

		// 🍕 仓库
		let FR_CK = [
			{ Left: "(", FieldName: "F_QUQY_StoreType", Compare: "=", Value: "公司仓", Right: ")", Logic: "and", filterFlag: "jc", R: 5 },
			{ Left: "(", FieldName: "FUseOrgId", Compare: "=", Value: memberInfo.F_QUQY_COMPANY_Id, Right: ")", Logic: "or", filterFlag: "jc", R: 5 },
			{ Left: "(", FieldName: "F_QUQY_Technician", Compare: "=", Value: memberInfo.Id, Right: ")", Logic: "and", R: 5 },
		]
		findIndexFun('QUQY_VeterinaryDrugStock', FR_CK)

		// 🍕 养殖户
		let FR_YZH = [
			{ "Left": "(", "FieldName": "FUseOrgId", "Compare": "=", "Value": memberInfo.F_QUQY_COMPANY_Id, "Right": ")", "Logic": "and", R: 3 },
		]
		findIndexFun('BD_Customer', FR_YZH)
		// 🍕 用户不存在 0
		if (myInfo.role.includes(1)) {
			let isBack = handleId(myInfo.UserId)
			if(isBack) uni.navigateBack()
			let isBack2 = handleId(userInfo.F_QUQY_Driver_Id)
			if(isBack || isBack2) uni.navigateBack()
			// 司机
			// 🍕 列表权限
			// 饲料申请： 创建人是自己的，未结算的
			let FR = [{ "Left": "(", "FieldName": "F_QUQY_CREATORID", "Compare": "=", "Value": myInfo.UserId, "Right": ")", "Logic": "and" }]
			findIndexFun('QUQY_FeedApplication', FR)

			// 饲料出库： 拉料司机是自己的
			let FR1 = [{ "Left": "(", "FieldName": "F_QUQY_PullingDriver1", "Compare": "=", "Value": userInfo.F_QUQY_Driver_Id, "Right": ")", "Logic": "and" }]
			findIndexFun('QUQY_SalesDeliveryOrder', FR1)

			// // 🍕 饲料按照饲料供应商来筛选
			// let FR3 = []
			// findIndexFun('BD_MATERIAL', FR3)

		}
		if (myInfo.role.includes(3)) {
			let isBack = handleId(memberInfo.Id)
			if(isBack) uni.navigateBack()
			let isBack2 = handleId(userInfo.Id)
			if(isBack || isBack2) uni.navigateBack()
			// 业务员
			// 🍕 列表权限
			// 上苗计划、养殖结算单： 业务员是自己的
			// let FR = []
			let FR = [{ "Left": "(", "FieldName": "F_QUQY_YWY", "Compare": "=", "Value": memberInfo.Id, "Right": ")", "Logic": "and" }]
			findIndexFun('QUQY_SeedPlan', FR)
			findIndexFun('QUQY_Settle', FR)
			findIndexFun('QUQY_YHSettle', FR)
			findIndexFun('QUQY_GetBreContract', FR)

			// 苗损列表： 创建人是自己的
			let FR1 = [{ "Left": "(", "FieldName": "F_QUQY_CREATORID", "Compare": "=", "Value": userInfo.Id, "Right": ")", "Logic": "and" }]
			findIndexFun('QUQY_LossInfoMiao', FR1)

		}
		if (myInfo.role.includes(5)) {
			let isBack = handleId(memberInfo.Id)
			if(isBack) uni.navigateBack()
			let isBack2 = handleId(userInfo.Id)
			if(isBack || isBack2) uni.navigateBack()
			
			// 技术员  隐藏
			// 🍕 列表权限
			// 兽药申请、兽药调拨申请： 创建人是自己的
			let FR = [{ "Left": "(", "FieldName": "F_QUQY_CREATORID", "Compare": "=", "Value": userInfo.Id, "Right": ")", "Logic": "and" }]
			// findIndexFun('QUQY_VeterinaryMedicineApplication', FR)
			findIndexFun('QUQY_TransferApplication', FR)

			// 兽药出库、兽药调拨、库存 技术员是自己的
			let FR1 = [{ "Left": "(", "FieldName": "F_QUQY_Technician", "Compare": "=", "Value": memberInfo.Id, "Right": ")", "Logic": "and" }]
			findIndexFun('QUQY_DrugOutbound', FR1)
			let FR2 = [{ "Left": "(", "FieldName": "F_QUQY_Applicant", "Compare": "=", "Value": memberInfo.Id, "Right": ")", "Logic": "and" }]
			findIndexFun('QUQY_VeterinaryDrugAllot', FR2)
			let FR3 = [{ "Left": "(", "FieldName": "F_QUQY_StockTech", "Compare": "=", "Value": memberInfo.Id, "Right": ")", "Logic": "and" }]
			findIndexFun('QUQY_VDInventoryTable', FR3)

		}
		if (myInfo.role.includes(7) || myInfo.role.includes(11)) {
			let isBack = handleId(memberInfo.F_QUQY_COMPANY_Id)
			if(isBack) uni.navigateBack()
			// 🍕 养殖场会计 7  所有单据只看到自己组织下的
			if(state.query.FormId === 'QUQY_YHSettle') {
				baseList.filter(it => (it.Type !== 1 && it.Type !== 3)).forEach(it => it.FilterString = [{ "Left": "(", "FieldName": "F_QUQY_ORGID", "Compare": "=", "Value": memberInfo.F_QUQY_COMPANY_Id, "Right": ")", "Logic": "and" }].concat(it.FilterString))
			} else {
				baseList.filter(it => (it.Type !== 1 && it.Type !== 3)).forEach(it => it.FilterString = [{ "Left": "(", "FieldName": "F_QUQY_ORGID", "Compare": "=", "Value": memberInfo.F_QUQY_COMPANY_Id, "Right": ")", "Logic": "and" }].concat(it.FilterString))
			}
		}

	}
</script>
<style lang="scss" scoped>
	.search-line {
		display: flex;
		align-items: center;
		height: 80rpx;
		padding: 0 30rpx;

		.search-btn {
			height: 60rpx;
			width: 120rpx;
			line-height: 60rpx;
			text-align: center;
			background: #2386ee;
			color: #fff;
			border-radius: 3rpx;
			margin-left: 20rpx;
		}
	}

	.search-input {
		width: 400rpx;
		height: 60rpx;
		border-radius: 3rpx;
		overflow: hidden;
		padding: 0 20rpx;
		background: #409eff10;
	}

	.list-line {
		position: relative;
		display: flex;
		align-items: center;
		width: calc(100% - 60rpx);
		min-height: 80rpx;
		line-height: 80rpx;
		margin: 0 auto;
		padding: 10rpx 30rpx 0 30rpx;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		margin-top: 20rpx;
		border-radius: 6rpx;
		white-space: nowrap;
		overflow: hidden;

		.active {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 30rpx;
			height: 30rpx;
			border: 1rpx solid #2386ee;
			background: #fff;
			border-radius: 50%;
			margin-right: 20rpx;
		}
	}

	.sum {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 80rpx;
		width: 100%;
		padding: 0 40rpx;
	}
</style>